import base64
import random
import string
from skimage import io
import cv2
import numpy as np
from keras.preprocessing import image
"""
图片编码
"""
def safe_base64_decode(s):
    data = (s.split("'")[1]).split("'")[0]
    img = base64.b64decode(data)
    with open('./1.jpg', 'wb') as f:
        f.write(img)
    return "./1.jpg"

"""
获取随机字符串
"""
def getRadomStr(n=5):
    if n<=0 and n>15:
        n=5
    ran_str = ''.join(random.sample(string.ascii_letters + string.digits, n))
    return ran_str


"""
根据路径加载图片
"""
def get_imageNdarrayFromDir(imageFilePath):
    image_ndarray = image.load_img(imageFilePath, target_size=(229, 229))
    image_ndarray = image.img_to_array(image_ndarray)
    return image_ndarray

"""
从Narray加载中图片
"""
def get_imageNdarrayFromNarray(imageNarray):
    image_ndarray = image.array_to_img(imageNarray)
    image_ndarray = image_ndarray.resize((229, 229))
    image_ndarray = image.img_to_array(image_ndarray)
    return image_ndarray

"""
图像预处，模型预测前必要的图像处理
"""
def rotate(image, angle=15, scale=0.9):
    w = image.shape[1]
    h = image.shape[0]
    # rotate matrix
    M = cv2.getRotationMatrix2D((w / 2, h / 2), angle, scale)
    # rotate
    image = cv2.warpAffine(image, M, (w, h))
    return image

"""
图像预处，模型预测前必要的图像处理
"""
def relight(imgsrc, alpha=1, bias=0):
    imgsrc = imgsrc.astype(float)
    imgsrc = imgsrc * alpha + bias
    imgsrc[imgsrc < 0] = 0
    imgsrc[imgsrc > 255] = 255
    imgsrc = imgsrc.astype(np.uint8)
    return imgsrc

"""
图像预处，模型预测前必要的图像处理
"""
def process_imageNdarray(image_ndarray):
    rgb_image_ndarray = image_ndarray[:, :, ::-1]
    rgb_image_ndarray = relight(rgb_image_ndarray, random.uniform(0.9, 1.1), random.randint(-10, 10))
    image_ndarray_1 = rgb_image_ndarray / 255.
    image_ndarray_1 = image_ndarray_1 - 0.5
    image_ndarray_1 = image_ndarray_1 * 2.
    crop = image_ndarray_1
    r1 = random.uniform(0.9, 1.1)
    r2 = random.randint(0, 45)
    crop = rotate(crop, angle=r2, scale=r1)
    flip = np.random.randint(0, 3)
    if flip == 1:
        flipimg = cv2.flip(crop, 1)
    if flip == 0:
        flipimg = cv2.flip(crop, 0)
    if flip == 2:
        flipimg = crop
    crop = cv2.resize(flipimg, (229, 229))
    crop = crop.reshape([1, 229, 229, 3])
    return crop

